﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AbstraX.Contracts;
using System.ServiceModel.DomainServices.Client;
using Mvvm;
using Microsoft.Practices.Unity;
using AbstraX;
using System.Collections.ObjectModel;
#if SILVERLIGHT
using AbstraX.ClientInterfaces;
#else
using AbstraX.ServerInterfaces;
#endif
using UIObjects.TreeViewInterfaces;
using MvvmTreeView;
using AbstraX.Bindings;
using System.Diagnostics;

namespace AbstraX.ViewModels.BindingsTree
{
    public class BindingsViewModel : BaseViewModel<IBindingsTreeService>, IBindingsViewModel
    {
        private BindingsTreeView treeView;

        public BindingsViewModel()
        {
            IUnityContainer container = ProviderLoader.Container;
            IBindingsTreeService model = container.Resolve<IBindingsTreeService>();
            IBindingsTreeCollection bindingsTrees;

            this.Model = model;

#if SILVERLIGHT
            bindingsTrees = this.Model.BindingsTrees;
            treeView = new BindingsTreeView(model, bindingsTrees);

            treeView.ImageList = new ImageList();
#endif
        }

        public ITreeView TreeView
        {
            get 
            {
                return treeView;
            }
        }

        private void Build(object sender)
        {
#if SILVERLIGHT
            var bindingsTrees = (IBindingsTreeCollection)sender;
            var service = this.Model;

            bindingsTrees.Cast<Entity>().ToList().ForEach(e =>
            {
                var invokeOperation = service.Build(e.GetID());

                invokeOperation.Completed += (sender2, e2) =>
                {
                    if (invokeOperation.HasError)
                    {
                        // Debugger.Break();
                    }
                };
            });
#endif
        }

        private bool CanBuild(object parm)
        {
            return true;
        }

        public MvvmCommand BuildCommand
        {
            get 
            {
                return new MvvmCommand(Build, CanBuild);
            }
        }

        public object CommandParameter
        {
            get 
            {
#if SILVERLIGHT
                return this.Model.BindingsTrees;
#else
                return null;
#endif
            }
        }
    }
}
